const db = require('../mysql')
const log4js = require('../utils/log4')
const logger = log4js.getLogger('server/router_handler/material.js')
const fileUpload = require('express-fileupload');
const fs = require('fs')
const path = require('path')
const { ...config } = require('../config/index');
const { generateUniqueCode } = require('../common/common')
/**
 * 
 * @param {String} str SQL命令 
 * @returns SQL命令返回数据
 */
exports.QueryDb = (str) =>{
    return new Promise((resolve,reject)=>{
        db.query(str,(err,res)=>{
            if(err){
                logger.error(err)
                reject(err)
            }
            resolve(res)
        })
    })
}
/**
 * 
 * @param {object} formdata对象仅限图片单传
 * @returns 文件名
 */
exports.savePhotoFile = async(formdata) => {
    if(!formdata) throw Error('缺少表单数据')
    if(formdata.size > (config.uploadPhotoSize * 1024 *1024)){
        throw Error('超出限制大小')
    }
    const mimeTypeToFileExtension = {  
        'image/jpeg': '.jpg',  
        'image/png': '.png',   
    }; 
    if(!mimeTypeToFileExtension.hasOwnProperty(formdata.mimetype)) throw Error('仅支持jpg&png')
    let name = `${formdata.md5}${mimeTypeToFileExtension[formdata.mimetype]}`
    await formdata.mv(path.join(__dirname, '../uploads/img/'+ name))
    return config.SystemUrl + 'img/' + name
}